<template>
    <a-upload
        v-model:file-list="fileList"
        name="file"
        :customRequest="hdlUpload"
        :progress="progress"
        :showUploadList="showUploadList"
        @remove="hdlRemoveFile"
        @download="hdlDownload"
        v-bind="$attrs"
        class="upload-box"
    >
        <slot :fileList="fileList" :loading="loading">
            <a-button>
                <UploadOutlined />
                上传文件
            </a-button>
        </slot>
        <template #downloadIcon>
            <EyeOutlined title="预览文件" />
        </template>
    </a-upload>
</template>

<script setup lang="ts">
    import { UploadOutlined, EyeOutlined } from "@ant-design/icons-vue";
    import { computed, ref, toRefs, watch } from "vue";
    import { UploadFile, UploadProps } from "ant-design-vue";
    import { tempUrl, uploadQiniu, initQiniuOssAxios } from "./qiniuOss";

    const props = withDefaults(
        defineProps<{
            uploadFileInfoList: any[];
            dirName?: string;
            fieldNames: any;
            mime: string;
            axios?: any;
        }>(),
        {
            uploadFileInfoList: () => [],
            dirName: "",
            fieldNames: {},
            mime: "text/plain",
        },
    );
    watch(
        () => props.axios,
        (newVal) => {
            if (newVal) {
                initQiniuOssAxios(newVal);
            }
        },
        {
            immediate: true,
        },
    );
    let defaultFieldNames = {
        name: "name",
        size: "size",
        type: "type",
        key: "key",
    };
    const { uploadFileInfoList, dirName, fieldNames } = toRefs(props);

    const fieldNamesObj = computed(() => {
        return Object.assign({}, defaultFieldNames, fieldNames.value);
    });

    const emit = defineEmits(["update:uploadFileInfoList"]);

    type FileInfo = {
        key: string;
        name: string;
        type: string;
        size: string;
        [props: string]: any;
    };
    const fileList = ref<FileInfo[]>([
        // {
        //     uid: 1,
        //     name: "logo2.png",
        //     status: "done",
        //     key:""
        // },
    ]);

    watch(
        () => uploadFileInfoList.value,
        (newValue, oldValue) => {
            if (oldValue && oldValue.length == 0) {
                fileList.value = newValue.map((item, i) => {
                    let uid = (Math.random() * 100000000).toFixed(0) + i;
                    item.uid = uid;
                    item.key = item[fieldNamesObj.value.key];
                    item.name = item[fieldNamesObj.value.name];
                    item.type = item[fieldNamesObj.value.type];
                    item.size = item[fieldNamesObj.value.size];
                    item.status = "done";
                    // if (item.file_name) {
                    //     item.name = item.file_name;
                    // } else if (item.name) {
                    //     item.file_name = item.name;
                    // }
                    return item;
                });
            }
        },
    );

    const progress: UploadProps["progress"] = {
        strokeWidth: 2,
        format: (percent: any) => `${parseFloat(percent.toFixed(2))}%`,
    };
    const showUploadList = {
        showPreviewIcon: true,
        showRemoveIcon: true,
        showDownloadIcon: true,
    };
    const loading = ref(false);
    const hdlUpload = async ({ file, onSuccess, onProgress }: any) => {
        loading.value = true;
        let res: any = await uploadQiniu(
            file,
            dirName.value,
            undefined,
            undefined,
            (percent: any) => {
                onProgress && onProgress({ percent, file });
            },
            true,
            props.mime,
        );
        onSuccess && onSuccess(res, file);
        loading.value = false;

        uploadFileInfoList.value.push({
            [fieldNamesObj["value"]["key"]]: res.key,
            [fieldNamesObj["value"]["size"]]: file.size,
            [fieldNamesObj["value"]["type"]]: file.type,
            [fieldNamesObj["value"]["name"]]: file.name,
            uid: file.uid,
        });

        // uploadFileInfoList.value.push({
        //     key: res.key,
        //     size: file.size,
        //     type: file.type,
        //     name: file.name,
        //     file_name: file.name,
        //     uid: file.uid,
        // });
        emit("update:uploadFileInfoList", uploadFileInfoList.value);
    };

    const hdlRemoveFile = (file: UploadFile) => {
        let files = uploadFileInfoList.value;
        let index = files.findIndex((item) => item.uid == file.uid);

        if (index != -1) {
            uploadFileInfoList.value.splice(index, 1);
            emit("update:uploadFileInfoList", uploadFileInfoList.value);
        }
    };

    const hdlDownload = async (file: UploadFile) => {
        let files = uploadFileInfoList.value;
        let obj = files.find((item) => item.uid == file.uid);

        if (obj) {
            let res = await tempUrl(obj.key);
            if (res) {
                window.open(res);
            }
        }
    };

    const changeFileList = (arr: FileInfo[]) => {
        fileList.value = [...fileList.value, ...arr];
    };

    defineExpose({
        changeFileList,
        hdlUpload,
    });
</script>

<style lang="scss" scoped src="./UploadAttachmentFile.scss"></style>
